package org.jeecg.common.rc.monitor;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.UUID;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Slf4j
//下面两个注解是必须的，少一个都不行哦
@Aspect
@Configuration
public class MonitorAop {

    @Autowired
    ObjectMapper objectMapper;

    //标记切入点，为指定包下的所有类的所有public方法

    @SneakyThrows
    @Around(value = "@annotation(org.jeecg.common.rc.monitor.Monitor)")
    public Object around(ProceedingJoinPoint joinPoint) {

        long startTime = System.currentTimeMillis();
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        Object object = null;
        try {
            object = joinPoint.proceed();
        } catch (Throwable e) {
            //打印入参
            Object[] args = joinPoint.getArgs();
            String arg = objectMapper.writeValueAsString(args);
            //打印出参
            String res = objectMapper.writeValueAsString(object);

            String requestId = UUID.randomUUID().toString().replace("-", "");

            log.info("请求id:::{}", requestId);
            log.info("方法名:::{}.{}() :::入参:::{}", className, methodName, arg);
            log.info("方法名:::{}.{}() :::出参:::{}", className, methodName, res);
            throw new RuntimeException(e);
        }
        long time = System.currentTimeMillis() - startTime;
        log.info("方法名:::{}.{}() 【执行时长为】:{}{}", className, methodName, time, " ms");
        return object;
    }
}
